<template>
<div >
<div style="margin: 10px 0;text-align: left ">

    <el-input class="search"
              placeholder="请输入内容"
              prefix-icon="el-icon-search"
              v-model="input"
              style="width: 300px; margin-right: 10px;"
    >
    </el-input>
    <el-button :icon="Icon.Search" circle @click="search" />

 
</div>

  <!--订单表格-->
  <div class="table" >
    <el-table ref="singleTable" :data="tableData"     stripe    border
              style=" height:600px;" :row-style="{height: '50px'}"
              :header-cell-style="{'text-align':'center'}"
              :cell-style="{'text-align':'center'}"
    >
      <el-table-column label="明细" type="expand" style="transition: all 0.5s;" width="60px">
        <template v-slot="{row}"  style="transition: all 0.5s;">
          <!--          订单商品信息详情-->
          <el-row>
            <!--            当前商品详情-->
            <el-col :span="10">
              <div>
                <div style="position: absolute;margin-top: 25px;margin-left: 45px;writing-mode: vertical-lr"><strong>当前商品</strong></div>
                <el-table :data="row.shoppingList"  :row-style="{height: '45px'}"  style="margin-left: 120px;"
                          :header-cell-style="{'text-align':'center'}"
                          :cell-style="{'text-align':'center'}"
                >
                  <el-table-column label="商品代码" prop="shoppingCode" width="100px"></el-table-column>
                  <el-table-column label="商品名称" prop="shoppingName" width="160px"></el-table-column>
                  <el-table-column label="商品数量" prop="shoppingNum" width="100px"></el-table-column>
                  <el-table-column label="商品单价(元)" prop="shoppingPrice" width="130px">1</el-table-column>
                  <!--                  <el-table-column label="总价" prop="shoppingSumPrice" width="100px">{{}}</el-table-column>-->
                </el-table>
              </div>
            </el-col>
            <!--            换货商品详情-->
            <el-col :span="10">
              <div v-if="row.type==='换货单'">
                <div style="position: absolute;margin-top: 25px;margin-left: 45px;writing-mode: vertical-lr"><strong>新的商品</strong></div>
                <el-table :data="row.newShoppingList" :row-style="{height: '45px'}"   style="margin-left: 120px">
                  <el-table-column label="商品代码" prop="shoppingCode" width="100px"></el-table-column>
                  <el-table-column label="商品名称" prop="shoppingName" width="160px"></el-table-column>
                  <el-table-column label="商品数量" prop="shoppingNum" width="100px"></el-table-column>
                  <el-table-column label="商品价格(元)" prop="shoppingPrice" width="130px"></el-table-column>
                  <!--    <el-table-column label="总价" prop="shoppingSumPrice" width="100px">{{}}</el-table-column>-->
                </el-table>
              </div>
            </el-col>
          </el-row>
        </template>
      </el-table-column>

      <el-table-column type="index" :index="getIndex" label="序号" width="60px">
      </el-table-column>
      <el-table-column label="订单编号" prop="oid" width=" 380px" style="text-align: center"></el-table-column>
      <el-table-column label="订单价格(元)" prop="totalPay" width="100px"></el-table-column>
      <el-table-column label="订单状态" width="90px">
        <template v-slot="scope">
          <el-tag effect="dark" size="mini" type="info" v-if="scope.row.status==='已完成订单'">已完成</el-tag>
          <el-tag effect="dark" size="mini" type="success"  v-else-if="scope.row.status==='已领货订单'">已签收</el-tag>
          <el-tag effect="dark" size="mini" type="danger" v-else-if="scope.row.status==='无效订单'">已取消</el-tag>
          <el-tag effect="dark" size="mini" type="warning" v-else>进行中</el-tag>

        </template>
      </el-table-column>
      <el-table-column label="订单类别" prop="type" width="100px"></el-table-column>
      <el-table-column label="下单时间" prop="buyTime" width="155px"></el-table-column>
      <el-table-column label="预计到达时间" prop="arriveTime" width="110px"></el-table-column>
<!--      <el-table-column label="发票信息" prop="receiptInfo" width="110px"></el-table-column>-->
      <el-table-column label="备注" prop="note" width="110px" ></el-table-column>


      <el-table-column label="操作" width="110px"  style="text-align: center">

        <template v-slot="scope">

          <el-dropdown @command="handleCommand" >
            <el-button type="warning" size="small" icon="Edit" style="font-size: 22px; margin-left: 15px;"></el-button>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item slot="reference" v-for="item in commands(scope.row)" v-show="isShowDropDown" :command="{status:item.command,oid:scope.row.oid,rowOrder:scope.row}">{{ item.action }}</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>



        </template>
      </el-table-column>

      <el-table-column label="物流信息" width="100px">
        <template v-slot="scope">
          <!--          <el-tooltip effect="dark" content="更改订单状态" placement="top" :enterable="false">-->
          <!--            <el-button type="warning" size="small" icon="Edit" style="font-size: 22px"  @click="changeOrderStatus(scope.row.oid)"></el-button>-->
          <el-tooltip effect="dark" content="查看物流信息" placement="top" :enterable="false">
            <el-button type="warning" size="small" icon="Van" style="font-size: 22px;margin-left: 10px"  @click="showTrans(scope.row)"></el-button>
          </el-tooltip>
        </template>
      </el-table-column>

    </el-table>
    <el-pagination
        background
        :page-size=pageSize
        layout="total, prev, pager, next"
        :total=totalSize
        @current-change="pageChange"
        style="margin-top: 15px"
        :current-page=pageNow
    >
    </el-pagination>
  </div>
  <el-dialog v-model="isShowForm" style=" border-radius: 20px;width: 450px">
    <el-timeline>
      <el-timeline-item v-for="item in transInfo" timestamp="" placement="top">
        <el-card>
          <h4>{{ item.action }}</h4>
          <p>{{item.time}}</p>
        </el-card>
      </el-timeline-item>
    </el-timeline>
  </el-dialog>



  <!--  换货的对话框-->
  <el-dialog
      title="换货商品"  v-model="isExchange"   style=" border-radius: 20px;width: 1100px">
    <el-row>
      <el-col :span="12" >

        <el-card class="exchange" style="display: inline-block">
          <h3>原商品</h3>
          <span  v-for="shopping in this.exchangOrder.shoppingList">{{shopping.shoppingName}} * {{shopping.shoppingNum}} </span>
          <span class="totalPay">合计 ￥ {{getTotalPay(this.exchangOrder.shoppingList)}}</span>

        </el-card>
      </el-col>
      <el-col :span="12" >

        <el-card  class="exchange"  style="display: inline-block">
          <h3>需要换货的商品</h3>
          <span  v-for="shopping in this.exchangOrder.newShoppingList">{{shopping.shoppingName}}
              <el-input-number v-model="shopping.shoppingNum" :min="0" :max="shopping.maxValues" style="width: 115px;float: right;margin-right: 150px"  />
          </span>
          <span class="totalPay">合计 ￥ {{getTotalPay(this.exchangOrder.newShoppingList)}}</span>
        </el-card>
      </el-col>
    </el-row>
    <el-button @click="isExchange=false">取消</el-button>
    <el-button @click="exchangeSubmit">确定</el-button>
  </el-dialog>
  <!--  换货的对话框-->


</div>

</template>

<script>
import cloneDeep from 'lodash/cloneDeep'
import {Delete, Edit, Search, Van} from "@element-plus/icons-vue";

import store from '@/store/index'
import {request_financial, request_user} from "@/util/request";
import {getDatetime} from "@/util/Utils";
import router from "@/router";

export default {
  name: "MyOrder",
  data() {
    return {
      Icon: {Delete, Edit, Search, Van},
      tableData: [{
        "oid": "2ff895f7d98dbb368c896ba3c7db4752",
        "status": "可分配订单",
        "type": "换货单",
        "recv": "史璐",
        "loc": "中国深圳罗湖区田贝一路260号12栋",
        "tele": "17705393085",
        "totalPay": 655.90,
        "shoppingList": [
          {
            "shoppingNum": 20,
            "shoppingName": "行李及旅行装备",
            "shoppingCode": "BGS-4659",
            "shoppingPrice": 61.07
          },

        ],
        "newShoppingList": [
          {
            "shoppingNum": 111,
            "shoppingName": "dabian",
            "shoppingCode": "7878783",
            "shoppingPrice": 61.07
          }
        ],
        "receiptInfo": "UnionPay",
        "note": "Wedding planner",
        "arriveTime": "2023-07-01",
        "buyTime": "2023-06-28 16:59:52"
      }],
      pageSize: 10,
      totalSize: 100,
      pageNow: 1,
      input: '',//搜索
      loading: false,
      isEdit0: false,
      isEdit1: false,
      AllOrders:[],
      form: {
        uid: '',
        username: '',
        tele: '',
        loc: ''
      },
      isShowForm: false,
      isShowDropDown:true,
      isExchange:false,
      OrderAction:{
        finish:"已完成订单",
        getShopping:"已领货订单",
        useless:"无效订单",
        delete:"删除订单",
        printReceipt:"打印发票",
        returnSale:"我要退货",
        exchangeSale:"我要换货"
      },
      transInfo:[],
      exchangOrder:{
        oid:'',
        shoppingList:[],
        newShoppingList:[]
      },
      orderTemp:{

      },
      //发票对象
      invoice:{
        orderId:"",
        loc:"辽宁省-沈阳市-和平区-西京街",
        batch:"311",
        buyName:store.state.user.username,
        buyIdentity:"142332200106150090",
        addressAndPhone:store.state.user.loc+" "+store.state.user.tele,
        account:"中国银行 200104",
        totalPrice:'',
        saleName:"DNA重组物流配送有限公司",
        saleIdentity:"146987199806065412",
        saleAccount:"中国银行 200108",
        saleAddressAndPhone:"辽宁省-沈阳市-和平区-西京街 6076223",
        getMoneyOne:"西索",
        review:"艾伦耶格尔",
        billing:"阿卡曼里维",
        note:"无",
        invoiceGoodInfoList:[]
      }


    }
  },
  methods:{
    search(){
      const filteredData = this.AllOrders.filter(order =>
          order.shoppingList.some(item => item.shoppingName.includes(this.input))
      );
      this.tableData=filteredData
    },
    showTrans(row){
      this.isShowForm=!this.isShowForm
        let transInfo = []
      const address = row.loc
      const parts = address.split('-');
      const resultAddress = parts[1] + '-' + parts[2];
        switch (row.status) {
          case "可分配订单":
            transInfo.push({action:"订单正在等待分配",time:row.buyTime})
                this.transInfo=transInfo
                return
          case "库房出库订单":
            transInfo.push({action:"订单正在等待分配",time:row.buyTime})
            transInfo.push({action:"商品已从中心库房出库",time:row.buyTime})
            this.transInfo=transInfo
            return
          case "已分配订单":
            transInfo.push({action:"订单正在等待分配",time:row.buyTime})
            transInfo.push({action:"商品已从中心库房出库",time:row.buyTime})
            transInfo.push({action:"商品已到达 "+resultAddress+" 分站库房，正在配送中",time:row.buyTime})
            this.transInfo=transInfo
            return
          case "已领货订单":
            transInfo.push({action:"订单正在等待分配",time:row.buyTime})
            transInfo.push({action:"商品已从中心库房出库",time:row.buyTime})
            transInfo.push({action:"商品已到达 "+resultAddress+" 分站库房，正在配送中",time:row.buyTime})
            transInfo.push({action:"您已领货",time:row.buyTime})
            this.transInfo=transInfo
            return
          case "已完成订单":
            transInfo.push({action:"订单正在等待分配",time:row.buyTime})
            transInfo.push({action:"商品已从中心库房出库",time:row.buyTime})
            transInfo.push({action:"商品已到达 "+resultAddress+" 分站库房，正在配送中",time:row.buyTime})
            transInfo.push({action:"您已领货",time:row.buyTime})
            transInfo.push({action:"订单已完成",time:row.buyTime})
            this.transInfo=transInfo
            return
          default:
            transInfo.push({action:"您已取消该订单",time:row.buyTime})
            this.transInfo=transInfo
            return
        }

    },

    getTotalPay(list){
      let sum =0
      list.forEach((item)=>{
        sum += item.shoppingPrice *item.shoppingNum
      })
      return sum
    },
    exchangeSubmit(){

      const order = store.state.order;
      order.oid = this.exchangOrder.oid
      order.recv=store.getters.getUserUid
      order.loc=store.getters.getUserLoc
      order.tele=store.getters.getUserTele
      order.type="换货单"
      order.newShoppingList=cloneDeep(this.exchangOrder.newShoppingList)
      //去掉无用的属性
      order.newShoppingList.forEach((shopping) => {
        delete shopping.maxValues;
      });
      order.buyTime = getDatetime("time")
      order.arriveTime = getDatetime("day")

      request_user.post("order/exchange", order).then(res=>{
        if(res.data.code===200){
          //成功
          this.$message({
            message: '换货成功',
            type: 'success'
          });
          this.isExchange=false
          this.getAllUserOrders()
        }else {
          this.$message({
            message: '换货失败',
            type: 'error'
          });
        }
      })
    },
    //表格索引获取
    getIndex(index) {
      index = index + 1 + (this.pageNow - 1) * this.pageSize
      return index
    },
    //分页换页
    pageChange(val) {
      this.pageNow = val
      this.getAllUserOrders()
    },
    //不同类型订单的操作不同
    commands(row){
      let editOrderStatus =[
        {action:"确认收货",command:"已完成订单"},
        {action:"取消订单",command:"无效订单"},
      ]
      let getShoppingOrder = [
        {action:"我要退货",command:"我要退货"},
        {action:"我要换货",command:"我要换货"},
        {action:"打印发票",command:"打印发票"},
        {action:"确认收货",command:"已完成订单"},
      ]
      let finishedOrder = [
        {action:"打印发票",command:"打印发票"},
        {action:"删除订单",command:"删除订单"}
      ]

      if(row.status===this.OrderAction.getShopping){
        return getShoppingOrder
      }else if(row.status===this.OrderAction.useless){
        return [{action:"删除订单",command:"删除订单"},]
      }else if(row.status===this.OrderAction.finish){
        return  finishedOrder
      }
      else {
        return editOrderStatus
      }

    },
    //修改订单状态
    /**
     command={
     status:  item.command,
     oid:  scope.row.oid,
     rowOrder:  scope.row
     }
     **/

    handleCommand(command){
      console.log(command.oid+"  "+command.status)
        //只有收货和取消可以更改状态
      if(command.status===this.OrderAction.useless||command.status===this.OrderAction.finish){
          //完善逻辑---如果已经完成不能够取消订单
          request_user.post("order/change",{
            oid:command.oid,
            status:command.status
          }).then(res=>{
            console.log(res.data)
            if (res.data.code===200){
              this.$message({
                message: '操作成功',
                type: 'success'
              });
              this.getAllUserOrders()
            }else {
              this.$message({
                message: '操作失败',
                type: 'error'
              });
            }
          })
      }else if(command.status===this.OrderAction.printReceipt){
        //打印发票的请求
          command.rowOrder.shoppingList.forEach((item)=>{
            const InvoiceGoodInfo = {
              specificationsModels :"无",
              measure:"克",
              rate:"0",
              tax:0.01,
              invoiceId:"",
              goodId:item.shoppingCode,
              goodName:item.shoppingName,
              goodCount:item.shoppingNum,
              price:item.shoppingPrice,
              goodOrderId:0
            };
          this.invoice.invoiceGoodInfoList.push(InvoiceGoodInfo)
            console.log(this.invoice.invoiceGoodInfoList)
          })
        this.invoice.orderId=command.oid
        this.invoice.totalPrice=command.rowOrder.totalPay
            request_financial.post("invoice/add",this.invoice).then(res=>{
              console.log(res.data)
              if (res.data.code === 200) {
                this.$message({
                  message: '打印成功',
                  type: 'success'
                });
                router.push({ name: 'receiptInfo', params: { oid: command.oid } });
              }else if(res.data.code===10011){
                router.push({ name: 'receiptInfo', params: { oid: command.oid } });
              }
              else {
                this.$message({
                  message: '打印失败',
                  type: 'error'
                });
              }
              this.invoice.invoiceGoodInfoList.length=0
            })
      }else{
            //在这里写退货和换货的流程
            if(command.status===this.OrderAction.returnSale){
              //退货请求
              request_user.post("order/returnSales",{
                oid:command.oid
              }).then(res=> {
                    console.log(res.data)
                    if (res.data.code === 200) {

                      this.$message({
                        message: '退货成功',
                        type: 'success'
                      });
                      this.getAllUserOrders()
                    }else{
                      this.$message({
                        message: '退货失败',
                        type: 'error'
                      });
                    }
                      //   request_financial.post("return").then(res=>{
                      //     console.log(res.data)
                      //     if(res.data.code===200){
                      //       this.$message({
                      //         message: '退货成功',
                      //         type: 'success'
                      //       });
                      //       this.getAllUserOrders()
                      //     }else{
                      //       this.$message({
                      //         message: '退货失败',
                      //         type: 'error'
                      //       });
                      //     }
                      //   })
                      // } else {
                      //   this.$message({
                      //     message: '退货失败',
                      //     type: 'error'
                      //   });
                      // }
                    }
                )







            }else if(command.status===this.OrderAction.exchangeSale) {
              //换货请求
              //alert("换货")
              this.exchangOrder.shoppingList=command.rowOrder.shoppingList
              this.exchangOrder.newShoppingList= cloneDeep(command.rowOrder.shoppingList)
              this.exchangOrder.oid=command.oid
              this.initializeMaxValues()
              this.isExchange=true

            }else if(command.status===this.OrderAction.delete){
              //删除
              this.$confirm('此操作将永久删除该订单, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
              }).then(() => {
                // **********************************
                //请求删除
                request_user.post("order/delete",{
                  oid:command.oid
                }).then(res=>{
                  console.log(res.data)
                  if(res.data.code===200){

                    this.$message({
                      message: '删除订单成功',
                      type: 'success'
                    });
                    this.getAllUserOrders()
                  }else {
                    this.$message({
                      message: '删除订单失败',
                      type: 'error'
                    });
                  }
                })
              // **********************************

              }).catch(() => {
                this.$message({
                  type: 'info',
                  message: '已取消删除'
                });
              });



          }
      }

    },
    initializeMaxValues() {
      this.exchangOrder.newShoppingList.forEach(shopping => {
       shopping.maxValues = shopping.shoppingNum
      });
    },
    //获取该用户的所有订单
    getAllUserOrders(){
      console.log(store.state.user.uid)
      request_user.post("order/userOrder",{
        uid:store.state.user.uid,
        pageNum: this.pageNow,
        pageSize: this.pageSize
      }).then(res=>{
        console.log(res.data)
        let data = res.data.data
        this.tableData = data.list;
        this.AllOrders=cloneDeep(this.tableData)
        this.tableData.forEach((item)=>{
          item.isPrintReceptInfo = false
        })
        this.totalSize = data.total
      })
    }
  },
  beforeMount() {
    this.getAllUserOrders()
    this.invoice.invoiceGoodInfoList.length=0
  },
  watch:{
    "input":{
      handler(n,o){
        if(n===''){
          this.getAllUserOrders()
        }
      }
    }
  }
}
</script>

<style scoped>
.exchange{
  display: inline-block;
  margin-left: 20px;
  width: 500px;
}
.exchange span{
 display: block;
  font-size: 18px;
  margin: 10px 0;
 text-align: left;
}
.totalPay{
  color: rgb(215, 50, 55);
}
</style>